/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.wms.web;

import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import com.jeeplus.modules.infor.entity.Goods;
import com.jeeplus.modules.infor.entity.Location;
import com.jeeplus.modules.infor.service.GoodsService;
import com.jeeplus.modules.infor.service.LocationService;
import com.jeeplus.modules.infor.service.PositionService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.wms.entity.*;
import com.jeeplus.modules.wms.mapper.MaterialParticularsMapper;
import com.jeeplus.modules.wms.mapper.StatisticsMapper;
import com.jeeplus.modules.wms.service.InventoryService;
import com.jeeplus.modules.wms.service.MaterialParticularsService;
import com.jeeplus.modules.wms.service.ReceivingNotesService;
import com.jeeplus.modules.wms.util.CopyUtil;
import com.jeeplus.modules.wms.util.ExportU;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.wms.service.StorageInformService;


/**
 * 入库通知Controller
 * @author sld
 * @version 2017-12-05
 */
@Controller
@RequestMapping(value = "${adminPath}/wms/storageInform")
public class StorageInformController extends BaseController {

	@Autowired
	private StorageInformService storageInformService;
	@Autowired
	private MaterialParticularsService materialParticularsService;
	@Autowired
	private ReceivingNotesService receivingNotesService;
	@Autowired
	private InventoryService   inventoryService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private LocationService locationService;
	@Autowired
	private MaterialParticularsMapper materialParticularsMapper;
	@Autowired
	private StatisticsMapper statisticsMapper;
	@Autowired
	private JdbcTemplate jdbc;
	@Autowired
	private PositionService positionService;

	@ModelAttribute
	public StorageInform get(@RequestParam(required = false) String id) {
		StorageInform entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = storageInformService.get(id);
		}
		if (entity == null) {
			entity = new StorageInform();
		}
		return entity;
	}
	/**
	 * 导出日统计
	 */
	@ResponseBody
	@RequestMapping(value = "daochu0")
	public void daochu0(HttpServletResponse response) {
		//获取数据
		List<Map<String,Object>> list=day();
		SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy年MM月dd日" );
		String str = sdf.format(new Date());
		ExportU e=new ExportU();
		e.export1(response,str,list);
	}
	/**
	 * 导出月统计
	 */
	@ResponseBody
	@RequestMapping(value = "daochu")
	public void daochu(HttpServletResponse response) {
		//获取数据
		List<Map<String,Object>> list=yue();
		SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy年MM月" );
		String str = sdf.format(new Date());
		ExportU e=new ExportU();
		e.export1(response,str,list);
	}
	/**
	 * 导出季度统计
	 */
	@ResponseBody
	@RequestMapping(value = "daochu1")
	public void daochu1(HttpServletResponse response) {
		//获取数据
		List<Map<String,Object>> list=jidu();
		SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy年" );
		String str = sdf.format(new Date())+"第"+(new Date().getMonth()%3+1)+"季度";
		ExportU e=new ExportU();
		e.export1(response,str,list);
	}


	/**
	 * 导出年统计
	 */
	@ResponseBody
	@RequestMapping(value = "daochu2")
	public void daochu2(HttpServletResponse response) {
		//获取数据
		List<Map<String,Object>> list=year();
		SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy年度" );
		String str = sdf.format(new Date());
		ExportU e=new ExportU();
		e.export1(response,str,list);
	}
	public  List<Map<String ,Object>> hb(List<Map<String ,Object>> list,List<Map<String ,Object>> lis){
		NumberFormat nf = NumberFormat.getInstance();
		for(Map<String,Object> m:list){
			boolean bo=false;
			for(Map<String,Object> map:lis){
				if(m.get("type").toString().equals(map.get("type").toString())&&m.get("name").toString().equals(map.get("name").toString())){
					bo=true;
				}
			}
			m.put("amount",nf.format(m.get("amount")));
			if(bo){
				for(Map<String,Object> map:lis){
					if(m.get("type").toString().equals(map.get("type").toString())&&m.get("name").toString().equals(map.get("name").toString())){
						m.put("outAmount",nf.format(map.get("amount")));

					}
				}

			}else{
				m.put("outAmount",0);
			}
		}
		List<Map<String ,Object>> list11=new ArrayList<>();
		for(Map<String,Object> m:lis){
			boolean bol=true;
			for(Map<String,Object> mm:list){
				if(m.get("type").toString().equals(mm.get("type").toString())&&m.get("name").toString().equals(mm.get("name").toString())){
					bol=false;
					break;
				}
			}
			if(bol){
				Map<String,Object> mm=new HashMap<String, Object>() ;
				mm.put("position",positionService.get(m.get("position").toString()).getName());
				mm.put("name",m.get("name"));
				mm.put("type",m.get("type"));
				mm.put("amount",0);
				mm.put("outAmount",nf.format(m.get("amount")));
				list11.add(mm);

			}
		}
		list.addAll(list11);
		return  list;
	}
	/**
	 * 当天的统计
	 */
	public List<Map<String,Object>> day(){
		String pro=UserUtils.getUseroffice();
		String sql="SELECT p.position AS position, p.`name` AS `name`,p.type AS type,SUM(p.workload) AS amount FROM `wms_statistics` p WHERE to_days(p.create_date) = to_days(now())and p.pro='"+pro+"' GROUP BY p.type,p. NAME ";
		String sq="SELECT p.position AS position, p.`name` AS `name`,p.type AS type,SUM(p.work) AS amount FROM `wms_outstatistics` p WHERE to_days(p.create_date) = to_days(now())and p.pro='"+pro+"' GROUP BY p.type,p. NAME";
		List<Map<String,Object>> list=jdbc.queryForList(sql);
		List<Map<String,Object>> lis=jdbc.queryForList(sq);
		list=hb(list,lis);
		return list;

	}
	/**
	 * 当月的统计
	 */
	public List<Map<String,Object>> yue(){
		String pro=UserUtils.getUseroffice();
		String sql="SELECT p.position AS position, p.`name` AS `name`,p.type AS type,SUM(p.workload) AS amount FROM `wms_statistics` p WHERE DATE_FORMAT( p.create_date, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' ) and p.pro='"+pro+"' GROUP BY p.type,p. NAME ";
		String sq="SELECT p.position AS position, p.`name` AS `name`,p.type AS type,SUM(p.work) AS amount FROM `wms_outstatistics` p WHERE DATE_FORMAT( p.create_date, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' ) and p.pro='"+pro+"' GROUP BY p.type,p. NAME";
		List<Map<String,Object>> list=jdbc.queryForList(sql);
		List<Map<String,Object>> lis=jdbc.queryForList(sq);
		list=hb(list,lis);
		return list;

	}

	/**
	 * 本季度的统计
	 */
	public List<Map<String,Object>> jidu(){
		String pro=UserUtils.getUseroffice();
		String sql="SELECT p.position AS position, p.`name` AS `name`,p.type AS type,SUM(p.workload) AS amount FROM `wms_statistics` p WHERE QUARTER(p.create_date)=QUARTER(now()) and p.pro='"+pro+"' GROUP BY p.type,p. NAME ";
		String sq="SELECT p.position AS position, p.`name` AS `name`,p.type AS type,SUM(p.work) AS amount FROM `wms_outstatistics` p WHERE QUARTER(p.create_date)=QUARTER(now()) and p.pro='"+pro+"' GROUP BY p.type,p. NAME";
     	List<Map<String,Object>> list=jdbc.queryForList(sql);
		List<Map<String,Object>> lis=jdbc.queryForList(sq);
		list=hb(list,lis);
		return list;

	}
	/**
	 * 本年度的统计
	 */
	public List<Map<String,Object>> year(){
		String pro=UserUtils.getUseroffice();
		String sql="SELECT p.position AS position, p.`name` AS `name`,p.type AS type,SUM(p.workload) AS amount FROM `wms_statistics` p WHERE YEAR(p.create_date)=YEAR(NOW()) and p.pro='"+pro+"' GROUP BY p.type,p. NAME ";
		String sq="SELECT p.position AS position, p.`name` AS `name`,p.type AS type,SUM(p.work) AS amount FROM `wms_outstatistics` p WHERE YEAR(p.create_date)=YEAR(NOW()) and p.pro='"+pro+"' GROUP BY p.type,p. NAME";
		List<Map<String,Object>> list=jdbc.queryForList(sql);
		List<Map<String,Object>> lis=jdbc.queryForList(sq);
		list=hb(list,lis);
		return list;

	}

	/**
	 * 出入库统计
	 * @return
	 */
	@RequestMapping(value="sum")
	public  String sum(Model model){
		model.addAttribute("lis",day());

		model.addAttribute("lis1",yue());

		model.addAttribute("lis2",jidu());

		model.addAttribute("lis3",year());

		return "modules/wms/sum";
	}
	/**
	 * 入库通知列表页面
	 */
	@RequiresPermissions("wms:storageInform:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/wms/storageInformList";
	}

	@RequiresPermissions("wms:storageInform:list")
	@RequestMapping(value = {"list1"})
	public String list1() {
		return "modules/wms/2/storageInformList";
	}

	@RequiresPermissions("wms:storageInform:list")
	@RequestMapping(value = {"list2"})
	public String list2() {
		return "modules/wms/3/storageInformList";
	}
	@RequiresPermissions("wms:storageInform:list")
	@RequestMapping(value = {"list4"})
	public String list4() {
		return "modules/wms/6/storageInformList";
	}

	/**
	 * 入库通知列表数据
	 */
	@ResponseBody
	@RequiresPermissions("wms:storageInform:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(StorageInform storageInform, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){storageInform.setProjectName(pro);}
		Page<StorageInform> page = storageInformService.findPage(new Page<StorageInform>(request, response), storageInform);
		return getBootstrapData(page);
	}
	/**
	 * 入库通知列表数据
	 */
	@ResponseBody
	@RequiresPermissions("wms:storageInform:list")
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(StorageInform storageInform, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){storageInform.setProjectName(pro);}
		storageInform.setState("收货完成");
		Page<StorageInform> page = storageInformService.findPage(new Page<StorageInform>(request, response), storageInform);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑入库通知表单页面
	 */
	@RequiresPermissions(value = {"wms:storageInform:view", "wms:storageInform:add", "wms:storageInform:edit"}, logical = Logical.OR)
	@RequestMapping(value = "form")
	public String form(StorageInform storageInform, Model model) {
		if(storageInform.getIsNewRecord()){
			storageInform.setStorageNumber(new Date().getTime()+"");
			String pro= UserUtils.getUseroffice();
			if(!pro.equals("总部")){storageInform.setProjectName(pro);}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String code=UserUtils.getUserAre()+sdf.format(new Date());
			StorageInform s=new StorageInform();
			s.setStorageNumber(code);
			List<StorageInform> l=storageInformService.findList(s);
			int i=l.size();
			for(StorageInform sto:l){
				if(sto.getStorageNumber().contains("-")){
					i-=1;
				}
			}
			if(l==null||i<1){
				storageInform.setStorageNumber(code+"001"+"RK");
			}else{
				if(i/10==0){
					storageInform.setStorageNumber(code+"00"+(i+1)+"RK");
				}else
				if(i/100==0){
					storageInform.setStorageNumber(code+"0"+(i+1)+"RK");
				}else{storageInform.setStorageNumber(code+(i+1)+"RK");}

			}


			storageInform.setState("已创建");
			if(pro.contains("润滑油")){storageInform.setShipperCode("CC");}else{
				storageInform.setShipperCode("YL");
			}

		}
		model.addAttribute("storageInform", storageInform);
		return "modules/wms/storageInformForm";

	}
  /**
  *  收货列表页面
   */
	@RequiresPermissions(value = {"wms:storageInform:view", "wms:storageInform:add", "wms:storageInform:edit"}, logical = Logical.OR)
	@RequestMapping(value = "form1")
	public String form1(StorageInform storageInform, Model model,ReceivingNotes receivingNotes,HttpServletRequest request) {
		model.addAttribute("storageInform", storageInform);
		return "modules/wms/2/storageInformForm";
	}
	/**
	 *  收货列表页面
	 */
	@RequestMapping(value = "form2")
	public String form2(StorageInform storageInform, Model model,ReceivingNotes receivingNotes,HttpServletRequest request) {
		model.addAttribute("storageInform", storageInform);
		return "modules/wms/6/storageInformForm";
	}
	/**
	 *  收货列表页面
	 */
	@RequestMapping(value = "form3")
	public String form3(StorageInform storageInform, Model model,ReceivingNotes receivingNotes,HttpServletRequest request) {
		model.addAttribute("storageInform", storageInform);
		return "modules/wms/7/storageInformForm";
	}
	/**
	 * 保存入库通知
	 */
	@ResponseBody
	@RequiresPermissions(value = {"wms:storageInform:add", "wms:storageInform:edit"}, logical = Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(StorageInform storageInform, Model model) throws Exception {
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, storageInform)) {
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		if(storageInform.getShippingNumber().length()<1){
			j.setSuccess(false);
			j.setMsg("请检查确定无误后保存！");
			return j;
		}
		for(MaterialParticulars m:storageInform.getMaterialParticularsList()){
			if(m.getForecast().length()<1||m.getMaterialCode().length()<1||m.getGoodsNumber().length()<1){
				j.setSuccess(false);
				j.setMsg("请检查确定无误后保存！");
				return j;
			}
		}
		storageInformService.save(storageInform);//保存

		//新增或编辑表单保存
		List<MaterialParticulars> l=storageInformService.get(storageInform.getId()).getMaterialParticularsList();
		boolean a=false;
		boolean b=false;
		boolean c=false;
		for(MaterialParticulars m:l){
			if(m.getState().contains("部分")){
                a=true;
			}
			if(m.getState().contains("完成")){
				b=true;
			}
			if(m.getState().contains("未")){
				c=true;
			}
		}
		if(!a&&b&&!c){
			storageInform.setState("收货完成");
		}else if(a||(b&c)){
			storageInform.setState("部分收货");
		}
		int sum=0;
		double avg=0.0;
        double m=0.0;
        double dg=0.0;
		double dx=0.0;
		double xx=0.0;
		double xht=0.0;
		double xt=0.0;
		double zt=0.0;
		double dt=0.0;
		double dai=0.0;
		double jian=0.0;
        String num="";
		   for(MaterialParticulars materialParticulars:l) {
		   	 if(storageInform.getId()!=null) {
		   	 	String typ=materialParticulars.getPacking();
		   	 	if(typ.equals("吨罐")){
		   	 		dg+=Double.parseDouble(materialParticulars.getRoughWeight());
				}
				 if(typ.equals("吨箱")){
					 dx+=Double.parseDouble(materialParticulars.getRoughWeight());
				 }
				 if(typ.equals("小箱")){
					 xx+=Double.parseDouble(materialParticulars.getRoughWeight());
				 }
				 if(typ.equals("小黄桶")){
					xht+=Double.parseDouble(materialParticulars.getRoughWeight());
				 }
				 if(typ.equals("小桶")){
					 xt+=Double.parseDouble(materialParticulars.getRoughWeight());
				 }
				 if(typ.equals("中桶")){
					 zt+=Double.parseDouble(materialParticulars.getRoughWeight());
				 }
				 if(typ.equals("大桶")){
					 dt+=Double.parseDouble(materialParticulars.getRoughWeight());
				 }
				 if(typ.equals("件")){
					 jian+=Double.parseDouble(materialParticulars.getRoughWeight());
				 }
				 if(typ.equals("袋")){
					 dai+=Double.parseDouble(materialParticulars.getRoughWeight());
				 }
				 m += Double.parseDouble(materialParticulars.getRoughWeight());
				 avg += Double.parseDouble(materialParticulars.getVolume());
				 sum += Integer.parseInt(materialParticulars.getForecast());
			     if(!num.contains(materialParticulars.getGoodsNumber())){num+=materialParticulars.getGoodsNumber()+",";}

			  }
		   }
		   storageInform.setDg(dg+"");
		storageInform.setDx(dx+"");
		storageInform.setXx(xx+"");
		storageInform.setXht(xht+"");
		storageInform.setXt(xt+"");
		storageInform.setZt(zt+"");
		storageInform.setDt(dt+"");
		storageInform.setDai(dai+"");
		storageInform.setJian(jian+"");
		NumberFormat nf = NumberFormat.getInstance();
		storageInform.setRoughWeight(nf.format(m));
		storageInform.setTotalVolume(nf.format(avg));
		storageInform.setForecast(sum+"");

        storageInform.setDeliveryNumber(num);
		List<Statistics> li=storageInform.getStatisticsList();
		if(li!=null&&li.size()>0){
			storageInform.setDjzt("已登记");
		}
		storageInformService.save(storageInform);//保存

		String type="";
		for(Statistics s:li){
			s.setPro(storageInform.getProjectName());
			if(type.contains(s.getPosition().getName())){
				continue;
			}else{
				type+=s.getPosition().getName()+",";
				if(s.getDg()!=null&&!"".equals(s.getDg())){
					continue;
				}else{
					double i=0;
					String  p=s.getPosition().getId();
					for(Statistics s1:li){
						if(s1.getPosition().getId().equals(p)){
							i++;
						}
					}
					for(Statistics s2:li){
						if(s2.getPosition().getId().equals(p)){
							s2.setDg(Double.parseDouble(storageInform.getDg())/i+"");
							s2.setDx(Double.parseDouble(storageInform.getDx())/i+"");
							s2.setXht(Double.parseDouble(storageInform.getXht())/i+"");
							s2.setXx(Double.parseDouble(storageInform.getXx())/i+"");
							s2.setXt(Double.parseDouble(storageInform.getXt())/i+"");
							s2.setZt(Double.parseDouble(storageInform.getZt())/i+"");
							s2.setDt(Double.parseDouble(storageInform.getDt())/i+"");
							s2.setJian(Double.parseDouble(storageInform.getJian())/i+"");
							s2.setDai(Double.parseDouble(storageInform.getDai())/i+"");
							statisticsMapper.update(s2);
						}
					}
				}
			}



		}
		j.setSuccess(true);
		j.setMsg("保存入库通知成功");
		return j;
	}
	/**
	 * 保存出库单
	 */
	@ResponseBody
	@RequiresPermissions(value={"wms:outbound:add","wms:outbound:edit"},logical=Logical.OR)
	@RequestMapping(value = "save1")
	public AjaxJson save1(StorageInform outbound, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		ReceivingNotes p=new ReceivingNotes();
		p.setPid(outbound.getId());
		List<ReceivingNotes> list=receivingNotesService.findList(p);
		List<MaterialParticulars> lis=outbound.getMaterialParticularsList();
		for(ReceivingNotes pi:list){
			pi.setZy(outbound.getShippingNumber());
			for(MaterialParticulars s:lis){
				if(s.getMaterialCode().equals(pi.getMaterialCoding())){
					pi.setJh(s.getGoodsNumber());
				}
			}
			receivingNotesService.save(pi);
		}
		storageInformService.save(outbound);
		j.setSuccess(true);
		j.setMsg("保存出库单成功");
		return j;
	}
	/**
	 * 删除入库通知
	 */
	@ResponseBody
	@RequiresPermissions("wms:storageInform:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(StorageInform storageInform, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		storageInformService.delete(storageInform);
		j.setMsg("删除入库通知成功");
		return j;
	}

	/**
	 * 取消入库
	 */
	@ResponseBody
	@Transactional(readOnly = false)
	@RequestMapping(value = "qxrk")
	public AjaxJson qxrk(StorageInform storageInform, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		ReceivingNotes r=new ReceivingNotes();
		r.setPid(storageInform.getId());
		r.setProjectName(storageInform.getProjectName());
		List<ReceivingNotes> notes=receivingNotesService.findList(r);
		for(ReceivingNotes no:notes){
			Inventory i=new Inventory();
			i.setProjectName(no.getProjectName());
			Location l=new Location();
			l.setName(no.getGoodsAllocation());
			l.setProjectName(no.getProjectName());
			i.setLocation(locationService.findList(l).get(0));
			i.setCode(no.getMaterialCoding());
			i.setPlace(no.getPackaging());
			i.setShipperCode(no.getOwnerCode());
			i.setBatch(no.getBatch());
			i.setBatchProperty(no.getTraceability());
			i.setExternalNumber(no.getDateRemark());
			List<Inventory> ll=inventoryService.findList(i);
			if(ll==null||ll.size()<1){
				j.setSuccess(false);
				j.setMsg("库存已经变化，不允许取消");
				return j;
			}
			i=ll.get(0);
            Double d=Double.parseDouble(i.getInventoryNumber());
			Double dd=Double.parseDouble(no.getQuantitiesReceived());
			if(Math.abs(dd)>Math.abs(d)){
				j.setSuccess(false);
				j.setMsg("库存已经变化，不允许取消");
				return j;
			}
		}
		for(ReceivingNotes n:notes){
			Inventory i=new Inventory();
			i.setProjectName(n.getProjectName());
			Location l=new Location();
			l.setName(n.getGoodsAllocation());
			l.setProjectName(n.getProjectName());
			i.setLocation(locationService.findList(l).get(0));
			i.setCode(n.getMaterialCoding());
			i.setPlace(n.getPackaging());
			i.setShipperCode(n.getOwnerCode());
			i.setBatch(n.getBatch());
			i.setBatchProperty(n.getTraceability());
			i.setExternalNumber(n.getDateRemark());
			List<Inventory> ll=inventoryService.findList(i);
			i=ll.get(0);
			Integer d=Integer.parseInt(i.getInventoryNumber());
			Integer dd=Integer.parseInt(n.getQuantitiesReceived());
			if(Math.abs(dd)==Math.abs(d)){
				inventoryService.delete(i);
			}else {
				i.setInventoryNumber(d-dd+"");
				i.setUsable(Integer.parseInt(i.getUsable())-dd+"");
				inventoryService.save(i);
			}
			receivingNotesService.delete(n);
		}
		storageInform.setState("已创建");
		storageInformService.save(storageInform);
		List<MaterialParticulars> ms=storageInform.getMaterialParticularsList();
		for(MaterialParticulars m:ms){
			m.setState("未入库");
			m.setQuantitiesReceived("0");
			materialParticularsService.save(m);
		}
		j.setSuccess(true);
		j.setMsg("取消入库成功");
		return j;
	}

	/**
	 * 批量删除入库通知
	 */
	@ResponseBody
	@RequiresPermissions("wms:storageInform:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] = ids.split(",");
		for (String id : idArray) {
			storageInformService.delete(storageInformService.get(id));
		}
		j.setMsg("删除入库通知成功");
		return j;
	}

	/**
	 * 拆单
	 */
	@ResponseBody
	@RequiresPermissions("wms:storageInform:del")
	@RequestMapping(value = "cd")
	public AjaxJson cd(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
       StorageInform s=storageInformService.get(ids);
		StorageInform si=new StorageInform();
		si= (StorageInform) CopyUtil.Copy(si,s,false);
       StorageInform st=new StorageInform();
       String code=s.getStorageNumber();
       if(!code.contains("-")){
       	si.setStorageNumber(code+"-1");
	   }else{
       st.setStorageNumber(code.substring(0,code.indexOf("-")));
       List<StorageInform> l=storageInformService.findList(st);
       si.setStorageNumber(code.substring(0,code.indexOf("-"))+"-"+l.size());
	   }
		si.setState("已创建");
		storageInformService.save(si);
       s.setState("收货完成");

      List<MaterialParticulars>  list=s.getMaterialParticularsList();
		int sum=0;
		double avg=0;
		double m0=0;

		int ss=0;
		double avg1=0;
		double m1=0;
		NumberFormat nf = NumberFormat.getInstance();
      for(MaterialParticulars m:list){
      	MaterialParticulars mm=new MaterialParticulars();
      	mm= (MaterialParticulars) CopyUtil.Copy(mm,m,false);
      	mm.setStorageInform(si);
      	if(Integer.parseInt(m.getQuantitiesReceived())==0){
      		materialParticularsService.save(mm);
			ss+=Integer.parseInt(mm.getQuantitiesReceived());
			avg1+=Double.parseDouble(mm.getVolume());
			m1+=Double.parseDouble(mm.getRoughWeight());
      		materialParticularsService.delete(m);
      		continue;
		}
		if(Integer.parseInt(m.getQuantitiesReceived())==Integer.parseInt(m.getForecast())){
			sum+=Integer.parseInt(m.getQuantitiesReceived());
			avg+=Double.parseDouble(m.getVolume());
			m0+=Double.parseDouble(m.getRoughWeight());
      		continue;
		}
		  Goods g=goodsService.get(m.getMaterialName().getId());
        mm.setState("未入库");
		int i=Integer.parseInt(m.getForecast())-Integer.parseInt(m.getQuantitiesReceived());
		mm.setForecast(i+"");
      	mm.setQuantitiesReceived("0");
      	mm.setWeight(nf.format(Double.parseDouble(g.getWeight())*i).replaceAll(",",""));
      	mm.setVolume(nf.format(Double.parseDouble(g.getVolume())*i).replaceAll(",",""));
      	mm.setRoughWeight(nf.format(Double.parseDouble(g.getGrossWeight())*i).replaceAll(",",""));
		materialParticularsService.save(mm);
      	m.setState("收货完成");
      	m.setForecast(m.getQuantitiesReceived());
        m.setVolume(nf.format(Double.parseDouble(g.getVolume())*Integer.parseInt(m.getQuantitiesReceived())).replaceAll(",",""));
        m.setRoughWeight(nf.format(Double.parseDouble(g.getGrossWeight())*Integer.parseInt(m.getQuantitiesReceived())).replaceAll(",",""));
		m.setWeight(nf.format(Double.parseDouble(g.getWeight())*Integer.parseInt(m.getQuantitiesReceived())).replaceAll(",",""));
      	materialParticularsMapper.update(m);
      	sum+=Integer.parseInt(m.getQuantitiesReceived());
      	avg+=Double.parseDouble(m.getVolume());
      	m0+=Double.parseDouble(m.getRoughWeight());
		  ss+=Integer.parseInt(mm.getQuantitiesReceived());
		  avg1+=Double.parseDouble(mm.getVolume());
		  m1+=Double.parseDouble(mm.getRoughWeight());
	  }
		s.setTotalVolume(nf.format(avg));
        s.setRoughWeight(nf.format(m0));
        s.setForecast(sum+"");
		si.setTotalVolume(nf.format(avg1));
		si.setRoughWeight(nf.format(m1));
		si.setForecast(ss+"");
		List<MaterialParticulars> ll=s.getMaterialParticularsList();
		double dg=0.0;
		double dx=0.0;
		double xx=0.0;
		double xht=0.0;
		double xt=0.0;
		double zt=0.0;
		double dt=0.0;
		for(MaterialParticulars materialParticulars:ll) {

				String typ=materialParticulars.getPacking();
				if(typ.equals("吨罐")){
					dg+=Double.parseDouble(materialParticulars.getRoughWeight());
				}
				if(typ.equals("吨箱")){
					dx+=Double.parseDouble(materialParticulars.getRoughWeight());
				}
				if(typ.equals("小箱")){
					xx+=Double.parseDouble(materialParticulars.getRoughWeight());
				}
				if(typ.equals("小黄桶")){
					xht+=Double.parseDouble(materialParticulars.getRoughWeight());
				}
				if(typ.equals("小桶")){
					xt+=Double.parseDouble(materialParticulars.getRoughWeight());
				}
				if(typ.equals("中桶")){
					zt+=Double.parseDouble(materialParticulars.getRoughWeight());
				}
				if(typ.equals("大桶")){
					dt+=Double.parseDouble(materialParticulars.getRoughWeight());
				}}
		s.setDg(dg+"");
		s.setDx(dx+"");
		s.setXx(xx+"");
		s.setXht(xht+"");
		s.setXt(xt+"");
		s.setZt(zt+"");
		s.setDt(dt+"");
		storageInformService.save(s);

		storageInformService.save(si);
		j.setMsg("拆单成功");
		return j;
	}
	@RequestMapping("findDetil")
	@ResponseBody
	public  MaterialParticulars findDetil(String i){
		MaterialParticulars m=materialParticularsService.get(i);
		m.setMaterialName(goodsService.get(m.getMaterialName().getId()));
		StorageInform s=storageInformService.get(m.getStorageInform().getId());
		m.setStorageInform(s);
		m.setRemarks(s.getProductionPlace());
		return m;
	}
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("wms:storageInform:export")
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public AjaxJson exportFile(StorageInform storageInform, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
			String fileName = "入库通知" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			Page<StorageInform> page = storageInformService.findPage(new Page<StorageInform>(request, response, -1), storageInform);
			new ExportExcel("入库通知", StorageInform.class).setDataList(page.getList()).write(response, fileName).dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出入库通知记录失败！失败信息：" + e.getMessage());
		}
		return j;
	}

	@ResponseBody
	@RequestMapping(value = "detail")
	public StorageInform detail(String id) {
		return storageInformService.get(id);
	}


	/**
	 * 导入Excel数据
	 */
	@RequiresPermissions("wms:storageInform:import")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file,Model model, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Import> list = ei.getDataList(Import.class);
			for (Import i : list) {
				try {
					String zy=i.getShipmentNumbers();
					String phone=i.getPhone();
					String truck=i.getTruckNumber();
					String jh=i.getNumber();
					String number=i.getAmount();
					String code=i.getCoding();
					String driver=i.getDriverName();
					StorageInform storageInform=new StorageInform();
					storageInform.setShippingNumber(zy);
					if(UserUtils.getUseroffice().contains("润滑油")){storageInform.setShipperCode("CC");}else{
						storageInform.setShipperCode("YL");
					}
					storageInform.setProjectName(UserUtils.getUseroffice());
					List<StorageInform> lis=storageInformService.findList(storageInform);
					if(lis!=null&&lis.size()>0){
                           storageInform=lis.get(0);
                           insert(storageInform,i);
						storageInform=storageInformService.get(storageInform.getId());
						this.save(storageInformService.get(storageInform),model);
					}else{
						SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
						String co=UserUtils.getUserAre()+sdf.format(new Date());
						StorageInform st=new StorageInform();
						st.setStorageNumber(co);
						List<StorageInform> li=storageInformService.findList(st);
						if(li==null||li.size()<1){
							storageInform.setStorageNumber(co+"001"+"RK");
						}else{
							if(li.size()/10==0){
								storageInform.setStorageNumber(co+"00"+(li.size()+1)+"RK");
							}else
							if(li.size()/100==0){
								storageInform.setStorageNumber(co+"0"+(li.size()+1)+"RK");
							}else{storageInform.setStorageNumber(co+(li.size()+1)+"RK");}

						}
						storageInform.setState("已创建");
						storageInform.setType("常规");
						storageInform.setStorageType("采购入库");
						storageInform.setNumber(truck);
						storageInform.setDriverPhone(phone);
						storageInform.setDriverName(driver);
						storageInformService.save(storageInform);
						insert(storageInform,i);
						storageInform=storageInformService.get(storageInform.getId());
						this.save(storageInformService.get(storageInform),model);
					}

					successNum++;
				} catch (ConstraintViolationException ex) {
					failureNum++;
				} catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条入库通知记录。");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条入库通知记录" + failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入入库通知失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/wms/storageInform/?repage";
	}

	private void insert(StorageInform storageInform, Import i) {
		MaterialParticulars m=new MaterialParticulars();
		m.setStorageInform(storageInform);
		List<MaterialParticulars>list=materialParticularsService.findList(m);
		if(list!=null&&list.size()>0){
			m.setIdx(list.size());
		}else{
			m.setIdx(0);
		}
		m.setMaterialCode(i.getCoding());
		Goods g=new Goods();
		g.setProject(UserUtils.getUseroffice());
		g.setCode(i.getCoding());
		g=goodsService.findList(g).get(0);
		g=goodsService.get(g.getId());
		m.setMaterialName(g);
		m.setState("未入库");
		m.setQuantitiesReceived("0");
		m.setMaterialSpecification(g.getSpecifications());
		m.setForecast(i.getAmount());
		m.setPackingUnit(g.getPacking());
		m.setPacking(g.getType().getName());
		Double weight=Double.parseDouble(g.getGrossWeight());
		Double volum =Double.parseDouble(g.getVolume());
		NumberFormat nf = NumberFormat.getInstance();
		m.setRoughWeight(nf.format(weight*Integer.parseInt(i.getAmount())).replaceAll(",",""));
		m.setVolume(nf.format(volum*Integer.parseInt(i.getAmount())).replaceAll(",",""));
		m.setGoodsNumber(i.getNumber());
       materialParticularsService.save(m);
	}

	/**
	 * 下载导入入库通知数据模板
	 */
	@RequiresPermissions("wms:storageInform:import")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "入库通知数据导入模板.xlsx";
			List<StorageInform> list = Lists.newArrayList();
			new ExportExcel("入库通知数据", Import.class, 1).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/wms/storageInform/?repage";
	}

	/**
	 *
	 */
	public String publicse(HttpServletRequest request) throws ParseException {
		String hid=request.getParameter("hid");
		MaterialParticulars materialParticulars=materialParticularsService.get(hid);
		StorageInform sto=storageInformService.get(materialParticulars.getStorageInform().getId());

		if(Integer.parseInt(request.getParameter("quantitiesReceived"))!=0){
		Date datel = null;
		ReceivingNotes notes = new ReceivingNotes();
		String storagesNumber = request.getParameter("storagesNumber");
		notes.setStoragesNumber(storagesNumber);
		notes.setPid(materialParticulars.getStorageInform().getId());
		String lineNumber = request.getParameter("lineNumber");
		notes.setLineNumber(lineNumber);
		String dealNumber = request.getParameter("dealNumber");
		notes.setDealNumber(dealNumber);
		String status = request.getParameter("status");
		notes.setStatus(status);
		String lpn = request.getParameter("lpn");
		notes.setLpn(lpn);
		String cases = request.getParameter("cases");
		notes.setCases(cases);
		String materialCoding = request.getParameter("materialCoding");
		notes.setMaterialCoding(materialCoding);
		String materialName = request.getParameter("materialName");
		notes.setMaterialName(materialName);
		String packaging = request.getParameter("packaging");
		notes.setPackaging(packaging);
		String units = request.getParameter("units");
		notes.setUnits(units);
		String expect = request.getParameter("expect");
		notes.setExpect(expect);
		String alreadyReceive = request.getParameter("alreadyReceive");
		notes.setAlreadyReceive(alreadyReceive);
		String quantitiesReceived = request.getParameter("quantitiesReceived");
		notes.setQuantitiesReceived(quantitiesReceived);
		String await = request.getParameter("await");
		notes.setAwait(await);
		String putawayNumber = request.getParameter("putawayNumber");
		notes.setPutawayNumber(putawayNumber);
		String allocationNumber = request.getParameter("allocationNumber");
		notes.setAllocationNumber(allocationNumber);
		String goodsAllocation = request.getParameter("goodsAllocation");

		String codeFreeze = request.getParameter("codeFreeze");
		notes.setCodeFreeze(codeFreeze);
		String cause = request.getParameter("cause");
		notes.setCause(cause);
		String storageDate = request.getParameter("storageDate");
			Date sa=null;
		if (StringUtils.isNotEmpty(storageDate)) {
			SimpleDateFormat dd = new SimpleDateFormat("yyyy-MM-dd");
			 sa = dd.parse(storageDate);
			notes.setStorageDate(sa);
		}
		String ownerCode = request.getParameter("ownerCode");
		notes.setOwnerCode(ownerCode);
		String supplierCode = request.getParameter("supplierCode");
		notes.setSupplierCode(supplierCode);
		String poNumber = request.getParameter("poNumber");
		notes.setPoNumber(poNumber);
		String volume = request.getParameter("volume");
		notes.setVolume(volume);
		String roughWeight = request.getParameter("roughWeightss");
		notes.setRoughWeight(roughWeight);
		String suttle = request.getParameter("suttle");
		notes.setSuttle(suttle);
		String lengths = request.getParameter("lengths");
		notes.setLengths(lengths);
		String wide = request.getParameter("wide");
		notes.setWide(wide);
		String tall = request.getParameter("tall");
		notes.setTall(tall);
		String qualityTesting = request.getParameter("qualityTesting");
		notes.setQualityTesting(qualityTesting);
		String adjustment = request.getParameter("adjustment");
		notes.setAdjustment(adjustment);
		String badnessCause = request.getParameter("badnessCause");
		notes.setBadnessCause(badnessCause);
		String property = request.getParameter("property");
		notes.setProperty(property);
		String propertyOne = request.getParameter("propertyOne");
		notes.setPropertyOne(propertyOne);
		String propertyTwo = request.getParameter("propertyTwo");
		notes.setPropertyTwo(propertyTwo);
		String production = request.getParameter("production");
		notes.setProduction(production);
		String traceability = request.getParameter("traceability");
		notes.setTraceability(traceability);
		String dateRemark = request.getParameter("dateRemark");
		notes.setDateRemark(dateRemark);
		String scan = request.getParameter("scan");
		notes.setScan(scan);
		String properties = request.getParameter("properties");
		notes.setProperties(properties);
		String dates = request.getParameter("dates");
			Date date = null;
		if (StringUtils.isNotEmpty(dates)) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			 date = sdf.parse(dates);
			notes.setDates(date);
		}
		String practicalDate = request.getParameter("practicalDate");

		if (StringUtils.isNotEmpty(practicalDate)) {
			SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
			datel = sd.parse(practicalDate);
			notes.setPracticalDate(datel);
		}
		String batch = request.getParameter("batch");
		notes.setBatch(batch);
		String remarks = request.getParameter("remarks");
		notes.setProperties(sto.getStorageType());
		notes.setRemarks(remarks);
		notes.setProjectName(UserUtils.getUseroffice());
		notes.setJh(materialParticulars.getGoodsNumber());
		StorageInform s=storageInformService.get(materialParticulars.getStorageInform());
		notes.setZy(s.getShippingNumber());
		notes.setStoragesNumber(s.getStorageNumber());
		notes.setWorkType(storageInformService.get(materialParticulars.getStorageInform().getId()).getType());
			int sy=Integer.parseInt(materialParticulars.getForecast())-Integer.parseInt(materialParticulars.getQuantitiesReceived());
		int sh=Integer.parseInt(quantitiesReceived);
		if(sy==sh){
			materialParticulars.setQuantitiesReceived(materialParticulars.getForecast());
			materialParticulars.setState("收货完成");
		}else{
			materialParticulars.setState("部分收货");
			materialParticulars.setQuantitiesReceived((Integer.parseInt(quantitiesReceived)+Integer.parseInt(materialParticulars.getQuantitiesReceived()))+"");
		}
		materialParticularsService.save(materialParticulars);
			Inventory i = new Inventory();
			i.setName(goodsService.get(request.getParameter("goods")));
			String goodsAllocationId = request.getParameter("goodsAllocationId");
			Location loc=new Location();
			if(goodsAllocation==""||goodsAllocation.length()<1){

				loc.setProjectName(UserUtils.getUseroffice());
				loc.setName("虚拟");
				List<Location> lc=locationService.findList(loc);
				loc=lc.get(0);

				goodsAllocation=loc.getName();
			}
			notes.setGoodsAllocation(goodsAllocation);
			if(goodsAllocationId==""||goodsAllocationId.length()<1){
				goodsAllocationId=loc.getId();
			}
			i.setLocation(locationService.get(goodsAllocationId));
			i.setPlace(packaging);
			i.setBatch(batch);
			i.setData(date);
			i.setExternalNumber(dateRemark);
			i.setBatchProperty(traceability);
			i.setCode(materialCoding);
			i.setShipperCode(ownerCode);
			i.setProjectName(UserUtils.getUseroffice());
			List<Inventory> l = inventoryService.findList(i);
			if (l == null || l.size() < 1) {
				notes.setZq("0");
				notes.setZh(quantitiesReceived);
				i.setStatus(status);
				i.setData(sa);
				i.setGoodsProperty(properties);
				i.setAllocation("0");
				i.setPackaging(packaging);
				i.setAllocation("0");
				i.setInboundDate(new Date());
				i.setUsable(quantitiesReceived);
				i.setInventoryNumber(quantitiesReceived);
               	inventoryService.save(i);
			}else {
				Inventory  m=l.get(0);
				notes.setZq(m.getUsableStandard());
				m.setUsable((Integer.parseInt(m.getUsable())+Integer.parseInt(quantitiesReceived))+"");
				m.setInventoryNumber((Integer.parseInt(m.getInventoryNumber())+Integer.parseInt(quantitiesReceived))+"");
				inventoryService.save(m);
				notes.setZh(m.getUsableStandard());
			}
			receivingNotesService.save(notes);
		}


			return "";
		}

		@ResponseBody
		@RequestMapping("saveStorageInform")
		public String saveStorageInform (Inventory inventory, StorageInform storageInform, HttpServletRequest
		request, HttpServletResponse response, RedirectAttributes redirectAttributes) throws ParseException {
			publicse(request);
			return "";
		}




}